#!/usr/bin/python3
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-

import os
import re
import sys
import codecs
import getpass
import subprocess


def add_or_update_line(linelist, key, value, force_update):
    found = False
    for i in range(0, len(linelist)):
        if re.match("^%s=(.*)$" % (key), linelist[i]) is not None:
            if force_update:
                linelist[i] = key + "=" + str(value)
            found = True
            break
    if not found:
        linelist.append(key + "=" + str(value))


def get_screen_resolution():
    out = subprocess.check_output(["xrandr"]).decode("ascii")
    m = re.search("(\\d+)x(\\d+).*\\*", out, re.M)
    return (int(m.group(1)), int(m.group(2)))


username = sys.argv[1]
cfg_dir = sys.argv[2]
sn_file = os.path.join(cfg_dir, "CD-KEY.txt")
settings_file = os.path.join(cfg_dir, "Save", "settings.dat")

linelist = []
if os.path.exists(settings_file):
    with codecs.open(settings_file, "r", "utf-16") as f:
        buf = f.read()
    linelist = buf.split("\r\n")
    linelist = [x for x in linelist if x != ""]

if True:
    sn = ""
    if os.path.exists(sn_file):
        with open(sn_file, "r") as f:
            sn = f.read().rstrip("\n")
    add_or_update_line(linelist, "CD KEY", sn, True)

add_or_update_line(linelist, "CHECK_DAY", 0, False)
add_or_update_line(linelist, "FOG", 1, False)
add_or_update_line(linelist, "FULL SCREEN", 1, False)
add_or_update_line(linelist, "GFX TYPE", 2, False)
add_or_update_line(linelist, "GLARE", 1, False)
add_or_update_line(linelist, "LOCOPACK", "us", False)
add_or_update_line(linelist, "LOWCOLORS", 0, False)
add_or_update_line(linelist, "MUSIC VOLUME", 40, False)

add_or_update_line(linelist, "PLAYER NAME", username, True)

add_or_update_line(linelist, "PTCL QUALITY", 2, False)

resx, resy = get_screen_resolution()
add_or_update_line(linelist, "RES_H", resy, False)
add_or_update_line(linelist, "RES_W", resx, False)

add_or_update_line(linelist, "RL LIGHTING", 1, False)
add_or_update_line(linelist, "SCENE DETAIL", 2, False)
add_or_update_line(linelist, "SHADOWS", 1, False)
add_or_update_line(linelist, "TXT QUALITY", 2, False)
add_or_update_line(linelist, "TXT SHARP", 0, False)
add_or_update_line(linelist, "TXTF QUALITY", 2, False)
add_or_update_line(linelist, "UNLOCKED MAP", "-1437404014", False)
add_or_update_line(linelist, "VOLUME", 50, False)
add_or_update_line(linelist, "WEATHER", 1, False)

with codecs.open(settings_file, "w", "utf-16") as f:
    for line in linelist:
        f.write(line + "\r\n")

